/*
 * Name: $RCSfile: InboxReadMessageActivity.java,v $
 * Version: $Revision: 1.1 $
 * Date: $Date: Nov 24, 2011 11:00:23 AM $
 *
 * Copyright (C) 2011 COMPANY_NAME, Inc. All rights reserved.
 */

package com.seta.medtalkdroid.app.screen.sentmessage;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.seta.medtalkdroid.app.R;
import com.seta.medtalkdroid.app.database.model.MessageModel;
import com.seta.medtalkdroid.app.gui.adapter.InboxMainMessageAdapter;
import com.seta.medtalkdroid.app.info.Define;
import com.seta.medtalkdroid.app.info.MedtalkSharedPreferences;
import com.seta.medtalkdroid.app.info.WebServiceConfig;
import com.seta.medtalkdroid.app.json.FriendInfo;
import com.seta.medtalkdroid.app.json.NotificationInfo;
import com.seta.medtalkdroid.app.json.ParserUtility;
import com.seta.medtalkdroid.app.json.ProfileInfo;
import com.seta.medtalkdroid.app.json.UserInfo;
import com.seta.medtalkdroid.app.network.AsyncHttpBase;
import com.seta.medtalkdroid.app.network.AsyncHttpPost;
import com.seta.medtalkdroid.app.network.AsyncHttpResponseListener;
import com.seta.medtalkdroid.app.network.AsyncHttpResponseProcess;
import com.seta.medtalkdroid.app.network.ParameterFactory;
import com.seta.medtalkdroid.app.screen.compose.ComposeUserDetailActivity;
import com.seta.medtalkdroid.app.screen.message.InboxBaseActivity;
import com.seta.medtalkdroid.app.utility.SmartLog;
import com.seta.medtalkdroid.app.utility.StringUtility;
import com.seta.medtalkdroid.app.xmpp.XmppManager;

/**
 * Inbox reading message activity
 * 
 * @author shforever distance message remind or message normal
 */
public class ReadSentMessage extends InboxBaseActivity implements Define,
        OnClickListener
{
    /**
     * change UI author shforever
     */
    private TextView tvTo, tvSubject, tvDate, tvTitle, tvHide;
    private Button btReplyoption, btReplyAlloption, btForwardoption,
            btCanceloption, btResend;
    private ImageButton btComposeMessage, btReply, btTrash, btRefreshMessage;
    private Dialog dlgReplyOption;
    private Handler handler = new Handler();
    private WebView webView;

    // Bcc, Cc
    private LinearLayout lnBcc, ln_to, lnCc;
    private View line22, line211, line21;
    private String positionOfMessage = "";

    private FriendInfo friendInfo;
    // Data

    // define key for send data to ComposeSendMessageActivity, for "reply",
    // "reply all", "forward"
    public static final String TO_FIELD = "to_recipient";
    public static final String FROM_FIELD = "from_sender";
    public static final String SUBJECT_FIELD = "subject";
    public static final String BODY_FIELD = "message";
    // =============
    //
    private static final int REPLY_ONE_FLAG = 0;
    private static final int REPLY_ALL_FLAG = 1;
    private static final int FORWARD_FLAG = 2;
    // ==============
    private String from = "";
    private String subject = "";
    private String content = "";
    private boolean isReply = false;
    private boolean isDraft = false;
    private boolean isForward = false;
    private String threadId;
    private String messageIdBefore = "";
    private String sendToUserNames = "";
    private String[] toUserNames = null;
    private String sendCcUserNames = "";
    private String[] ccUserNames = null;
    private String sendBccUserNames = "";
    private String[] bccUserNames = null;

    public static int isDelete = -1;
    public static int position = -1;

    // -===================
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sent_read_message);
        initUI(savedInstanceState);

        Bundle b = this.getIntent().getExtras();
        // initNavigateUI();
        tvTitle = (TextView) findViewById(R.id.title);
        if (b != null)
        {
            tvTitle.setText(b.getInt("POSITION") + " of " + b.getInt("SIZE"));
            position = b.getInt("POSITION") - 1;
        }
        loadInboxMessageDetail();
    }

    @Override
    public void onResume()
    {
        super.onResume();
        // initStatusUI();

    }

    /**
     * Initial user interface
     */
    private void initUI(Bundle savedInstanceState)
    {
        /**
         * @author shforever
         */
        // action delete?
        isDelete = -1;
        position = -1;

        tvTo = (TextView) findViewById(R.id.to_detail_message);
        tvTo.setOnClickListener(this);

        tvSubject = (TextView) findViewById(R.id.subject_detail);
        tvDate = (TextView) findViewById(R.id.time_detail);
        webView = (WebView) findViewById(R.id.webView);
        webView.getSettings().setBuiltInZoomControls(false);
        // webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebChromeClient(new WebChromeClient());
        if (savedInstanceState != null)
        {
            webView.restoreState(savedInstanceState);
        }

        btResend = (Button) findViewById(R.id.resend);
        btResend.setOnClickListener(this);

        btTrash = (ImageButton) findViewById(R.id.trash_message);
        btTrash.setOnClickListener(this);

        btReply = (ImageButton) findViewById(R.id.reply_message);
        btReply.setOnClickListener(this);

        btComposeMessage = (ImageButton) findViewById(R.id.compose_message);
        btComposeMessage.setOnClickListener(this);

        btRefreshMessage = (ImageButton) findViewById(R.id.refresh_message);
        btRefreshMessage.setOnClickListener(this);

        initDialogQuickReply(this);

        ln_to = (LinearLayout) findViewById(R.id.ln_to);
        lnBcc = (LinearLayout) findViewById(R.id.ln_bcc);
        lnCc = (LinearLayout) findViewById(R.id.ln_cc);
        line22 = (View) findViewById(R.id.line22);
        line21 = (View) findViewById(R.id.line21);
        line211 = (View) findViewById(R.id.line211);

        tvHide = (TextView) findViewById(R.id.hide);
        tvHide.setOnClickListener(this);
        mainContent = "";

    }

    // ========================= Load messages =========================

    /**
     * Load detail messages
     */
    private void loadInboxMessageDetail()
    {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();

        // hientx - Check if message is remind message
        if (bundle != null)
        {
            // Get MessageID from bundle
            try
            {
                // Get IdNotify for cancel
                int notifyId = Integer.valueOf(bundle.getString("notifyId"));
                // Remove notify from listNotifyMessage
                app.notificationManager.cancel(notifyId);

                String messageId = (bundle.getString("messageId") != null) ? bundle.getString("messageId")
                    : "";

                int indexExist = -1;
                for (int i = 0; i < listNotifyMessage.size(); i++)
                {
                    if (listNotifyMessage.get(i).getMessageId().equalsIgnoreCase(
                        messageId))
                    {
                        // reset current message for display
                        MessageModel messageRemindCurrent = listNotifyMessage.get(i);
                        app.setCurrentInboxMessage(messageRemindCurrent);
                        indexExist = i;

                    }
                }

                if (indexExist >= 0)
                    listNotifyMessage.remove(indexExist);

            }
            catch (Exception ex)
            {
                SmartLog.log("test", "Error-------" + ex.toString());
            }
        }

        if (app.isNotifyNavigate())
        {
            app.setNotifyNavigate(false);
            loadDetailMessageFromServer(app.getNotificationInfo());
        }
        else
        {
            mainMessage = app.getCurrentInboxMessage();
            loadDetailMessageToUI();
        }
    }

    private void loadDetailMessageToUI()
    {
        if (mainMessage != null)
        {
            // fill message
            fillMessage(mainMessage);
            markMessageRead();

            messageDetail = new MessageModel();
            messageDetail = mainMessage;

        }
    }

    private void loadDetailMessageFromServer(NotificationInfo notifyInfo)
    {
        // Get user information
        UserInfo userInfo = MedtalkSharedPreferences.getInstance(
            getApplicationContext()).getUserInfo();
        String token = userInfo.getAccessToken();

        // Build get message detail parameters
        List<NameValuePair> parameters = ParameterFactory.createMessageReadByMessageIdParams(
            token, notifyInfo.getMessageId());

        // Get detail message from server
        AsyncHttpPost post = new AsyncHttpPost(self,
            new AsyncHttpResponseProcess(self) {

                public void processIfResponseSuccess(String response)
                {
                    mainMessage = ParserUtility.parserMessage(response);
                    try
                    {
                        positionOfMessage = ParserUtility.getPositionMessage(response);
                    }
                    catch (Exception e)
                    {
                    }
                    tvTitle.setText(positionOfMessage);
                    loadDetailMessageToUI();
                }

                public void processIfResponseFail()
                {
                    showToastMessage("Error to load message detail from server!");
                    gotoActivity(self, SentMessageMain.class,
                        Intent.FLAG_ACTIVITY_CLEAR_TOP);
                }

            }, parameters);
        post.execute(WebServiceConfig.URL_LOAD_MESSAGE_DETAIL);
    }

    /**
     * fill message into UI
     */
    private void fillMessage(MessageModel message)
    {
        tvSubject.setText(Html.fromHtml(message.getMessageSubject()));
        tvDate.setText(InboxMainMessageAdapter.getDate(message.getCreatedAt(),
            "MMM dd, yyyy h:mm aa"));
        createMainContent(message);
        mainContent += message.getMessageContent();
        mainContent = mainContent.replace("&nbsp", " ");
        mainContent = mainContent.replaceAll("<div class=\"previous\">", "</br>"+"<div class=\"previous\">");
        
        String displayContent = mofifyPreviousMessageGray(mainContent);
        mainContent="";
        webView.loadDataWithBaseURL(URL_BASE, displayContent, "text/html",
            "UTF-8", null);
        SmartLog.log(TAG, "Message display:" + displayContent);


        // Load GUI for From
        loadGUIFrom(message);

        // Load GUI for To
        loadGUITos(message);

        // Load GUI for Bcc
        loadGUIBccs(message);

        // Load GUI for Cc
        loadGUICcs(message);
    }

    /**
     * @author shforever
     * @param message
     */
    private void loadGUIFrom(final MessageModel message)
    {
        LinearLayout layoutFrom = (LinearLayout) findViewById(R.id.lnfrom);
        layoutFrom.removeAllViews();
        // Create new LayoutInflater
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.name_user, null);
        layoutFrom.addView(view);

        ImageView imageDetail = (ImageView) view.findViewById(R.id.detail);
        imageDetail.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                requestInformation(message.getMessageFromUserName());
                return false;
            }
        });
        ImageView imageIsRead = (ImageView) view.findViewById(R.id.isRead_detail);
        TextView tvName = (TextView) view.findViewById(R.id.name);
        tvName.setText(message.getMessageFromUserFullName());
        imageIsRead.setVisibility(View.GONE);
    }

    /**
     * @param message
     */
    private int sizeBcc;

    private void loadGUIBccs(final MessageModel message)
    {
        LinearLayout layoutBccs = (LinearLayout) findViewById(R.id.listBcc);
        layoutBccs.removeAllViews();
        sizeBcc = message.getMessageBccs().size();
        if (sizeBcc == 0)
        {
            lnBcc.setVisibility(View.GONE);
            line22.setVisibility(View.GONE);

        }
        else
        {
            for (int i = 0; i < sizeBcc; i++)
            {
                String userName = message.getMessageBccs().get(i).get(
                    "Username");

                // Create new LayoutInflater
                LayoutInflater inflater = getLayoutInflater();
                View view = inflater.inflate(R.layout.name_user, null);
                layoutBccs.addView(view);

                ImageView imageDetail = (ImageView) view.findViewById(R.id.detail);
                imageDetail.setTag(userName);
                imageDetail.setOnTouchListener(new OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event)
                    {
                        ImageView view = (ImageView) v;
                        String userName = view.getTag().toString();
                        // SmartLog.log(TAG, "User name detail:" + userName);
                        requestInformation(userName);
                        return false;
                    }
                });

                ImageView imageIsRead = (ImageView) view.findViewById(R.id.isRead_detail);

                TextView tvName = (TextView) view.findViewById(R.id.name);
                tvName.setText(message.getMessageBccs().get(i).get("FullName"));

                final String timeRead = message.getMessageBccs().get(i).get(
                    "ReadTime").toString();
                if (message.getMessageBccs().get(i).get("IsRead").equals("true"))
                {
                    imageIsRead.setOnLongClickListener(new OnLongClickListener() {

                        @Override
                        public boolean onLongClick(View v)
                        {
                            loadQuickAction(ReadSentMessage.this, v,
                                InboxMainMessageAdapter.getDate(timeRead,
                                    "MM/dd/yy h:mm aa"));
                            return false;
                        }
                    });

                }
                else
                {
                    imageIsRead.setImageResource(R.drawable.icon_check_mess_detail_transpa);
                }
            }
        }
    }

    /**
     * @param message
     */
    private int sizeCc;

    private void loadGUICcs(final MessageModel message)
    {
        LinearLayout layoutCcs = (LinearLayout) findViewById(R.id.listCc);
        layoutCcs.removeAllViews();
        sizeCc = message.getMessageCCs().size();
        if (sizeCc == 0)
        {
            lnCc.setVisibility(View.GONE);
            line21.setVisibility(View.GONE);

        }
        else
        {
            for (int i = 0; i < sizeCc; i++)
            {
                String userName = message.getMessageCCs().get(i).get("Username");

                // Create new LayoutInflater
                LayoutInflater inflater = getLayoutInflater();
                View view = inflater.inflate(R.layout.name_user, null);
                layoutCcs.addView(view);

                ImageView imageDetail = (ImageView) view.findViewById(R.id.detail);
                imageDetail.setTag(userName);
                imageDetail.setOnTouchListener(new OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event)
                    {
                        ImageView view = (ImageView) v;
                        String userName = view.getTag().toString();
                        // SmartLog.log(TAG, "User name detail:" + userName);
                        requestInformation(userName);
                        return false;
                    }
                });
                ImageView imageIsRead = (ImageView) view.findViewById(R.id.isRead_detail);

                TextView tvName = (TextView) view.findViewById(R.id.name);
                tvName.setText(message.getMessageCCs().get(i).get("FullName"));

                final String timeRead = message.getMessageCCs().get(i).get(
                    "ReadTime").toString();
                if (message.getMessageCCs().get(i).get("IsRead").equals("true"))
                {
                    imageIsRead.setOnLongClickListener(new OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v)
                        {
                            loadQuickAction(ReadSentMessage.this, v,
                                InboxMainMessageAdapter.getDate(timeRead,
                                    "MM/dd/yy h:mm aa"));
                            return false;
                        }
                    });

                }
                else
                {
                    imageIsRead.setImageResource(R.drawable.icon_check_mess_detail_transpa);
                }
            }
        }
    }

    /**
     * @author shforever
     * @param message
     */
    private void loadGUITos(final MessageModel message)
    {
        LinearLayout layoutTos = (LinearLayout) findViewById(R.id.listTos);
        layoutTos.removeAllViews();

        for (int i = 0; i < message.getMessageTos().size(); i++)
        {
            String userName = message.getMessageTos().get(i).get("Username");

            // Create new LayoutInflater
            LayoutInflater inflater = getLayoutInflater();
            View view = inflater.inflate(R.layout.name_user, null);
            layoutTos.addView(view);

            ImageView imageDetail = (ImageView) view.findViewById(R.id.detail);
            imageDetail.setTag(userName);
            imageDetail.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event)
                {
                    ImageView view = (ImageView) v;
                    String userName = view.getTag().toString();
                    // SmartLog.log(TAG, "User name detail:" + userName);
                    requestInformation(userName);
                    return false;
                }
            });
            ImageView imageIsRead = (ImageView) view.findViewById(R.id.isRead_detail);

            TextView tvName = (TextView) view.findViewById(R.id.name);
            tvName.setText(message.getMessageTos().get(i).get("FullName"));

            final String timeRead = message.getMessageTos().get(i).get(
                "ReadTime").toString();
            if (message.getMessageTos().get(i).get("IsRead").equals("true"))
            {
                imageIsRead.setOnLongClickListener(new OnLongClickListener() {

                    @Override
                    public boolean onLongClick(View v)
                    {
                        loadQuickAction(ReadSentMessage.this, v,
                            InboxMainMessageAdapter.getDate(timeRead,
                                "MM/dd/yy h:mm aa"));
                        return false;
                    }
                });

            }
            else
            {
                imageIsRead.setImageResource(R.drawable.icon_check_mess_detail_transpa);
            }

        }
    }

    public void requestInformation(String userName)
    {
        UserInfo userInfo = MedtalkSharedPreferences.getInstance(
            getApplicationContext()).getUserInfo();
        String token = userInfo.getAccessToken();

        // Build get friend list parameters
        List<NameValuePair> parameters = ParameterFactory.createGetInformationUserParams(
            token, userName);

        AsyncHttpPost post = new AsyncHttpPost(self,
            new AsyncHttpResponseProcess(self) {
                @Override
                public void processIfResponseSuccess(String response)
                {
                    processInformation(response);
                }

            }, parameters);

        post.execute(WebServiceConfig.URL_GET_MY_PROFILE);
    }

    private void processInformation(String response)
    {
        friendInfo = ParserUtility.parseFriendInfo(response);
        Bundle mBundle = new Bundle();
        mBundle.putString("action", "detail");
        mBundle.putString("groupId", "0");
        if (friendInfo != null)
        {
            mBundle.putParcelable(Define.FRIEND_INFO, friendInfo);
        }

        gotoActivity(self, ComposeUserDetailActivity.class, mBundle);
    }

    @Override
    public void onClick(View view)
    {
        if (view == btTrash)
        {
            showDialogTwo(getString(R.string.message_delete_messages_confirm),
                onDeleteDraftMessage, null);
        }
        else if (view == btResend)
        {
            // show timpicker to chose time reminder
            sendMessage();
        }
        else if (view == btReply)
        {
            showDialogReplyOption();
        }
        else if (view == btComposeMessage)
        {
            // move to compose activity;
            app.isReplyMessage = false;
            // gotoActivity(self, ComposeSendMessageActivity.class);
            gotoNewComposeActivity(self);
        }
        else if (view == btRefreshMessage)
        {
            loadInboxMessageDetail();
            Log.d("TOU", "Refresh");
        }
        else if (view == btCanceloption)
        {
            hideDialogReplyOption();
        }
        else if (view == btReplyoption)
        {
            // move to compose activity;
            gotoCompose(REPLY_ONE_FLAG, self);
            hideDialogReplyOption();
        }
        else if (view == btReplyAlloption)
        {
            // move to compose activity;
            gotoCompose(REPLY_ALL_FLAG, self);
            hideDialogReplyOption();
        }
        else if (view == btForwardoption)
        {
            // move to compose activity;
            gotoCompose(FORWARD_FLAG, self);
            hideDialogReplyOption();
        }
        else if (view == tvHide)
        {
            // hide and show To and Bcc;
            if (ln_to.isShown())
            {
                // if Layout contain To show--> hide To and Bcc
                ln_to.setVisibility(View.GONE);
                line21.setVisibility(View.GONE);
                lnBcc.setVisibility(View.GONE);
                line211.setVisibility(View.GONE);
                lnCc.setVisibility(View.GONE);
                line22.setVisibility(View.GONE);
                tvHide.setText("Show");
            }
            else
            {
                tvHide.setText("Hide");
                ln_to.setVisibility(View.VISIBLE);
                line21.setVisibility(View.VISIBLE);
                line211.setVisibility(View.VISIBLE);
                if (sizeBcc == 0)
                {
                    lnBcc.setVisibility(View.GONE);
                    line22.setVisibility(View.GONE);
                }
                else
                {
                    // if size of Bcc >0 --> have Bcc
                    lnBcc.setVisibility(View.VISIBLE);
                    line22.setVisibility(View.VISIBLE);
                }
                if (sizeCc == 0)
                {
                    lnCc.setVisibility(View.GONE);
                    line21.setVisibility(View.GONE);
                }
                else
                {
                    // if size of Bcc >0 --> have Bcc
                    lnCc.setVisibility(View.VISIBLE);
                    line21.setVisibility(View.VISIBLE);
                }

            }
        }
    }

    // =======================Mark Message Read===============================
    public void markMessageRead()
    {
        // Get user information
        UserInfo userInfo = MedtalkSharedPreferences.getInstance(
            getApplicationContext()).getUserInfo();
        String token = userInfo.getAccessToken();

        // Build get message detail parameters
        List<NameValuePair> parameters = ParameterFactory.createMarkInboxMessageReadParams(
            token, mainMessage.getPersonalMessageId());

        AsyncHttpPost post = new AsyncHttpPost(self,
            new AsyncHttpResponseListener() {

                @Override
                public void before()
                {
                    // show waiting dialog
                }

                @Override
                public void after(int statusCode, HttpResponse response)
                {
                    // Process server response
                    switch (statusCode)
                    {
                        case AsyncHttpBase.NETWORK_STATUS_OFF:
                            break;
                        case AsyncHttpBase.NETWORK_STATUS_OK:
                            // markMessageRead();
                            break;
                        default:
                            break;
                    }
                }
            }, parameters);
        post.execute(WebServiceConfig.URL_MARK_INBOX_MESSAGE_READ);
    }

    // ====================== Delete draft message ======================

    View.OnClickListener onDeleteDraftMessage = new View.OnClickListener() {

        @Override
        public void onClick(View v)
        {
            // Delete inbox message
            deleteDraftsMessage(mainMessage);
            dialog.dismiss();
        }
    };

    @Override
    public void processAfterDeleteDraftMessageSingle(String respone)
    {
        // action delete
        SmartLog.log(TAG, "posotpm" + position);
        isDelete = position;
        showToastMessage(R.string.message_delete_detail_message_successfully);
        app.clearInboxNotification();
        finish();

    }

    // ====================== Archive inbox message ======================

    View.OnClickListener onArchiveInboxMessage = new View.OnClickListener() {

        @Override
        public void onClick(View v)
        {
            archiveInboxMessage(mainMessage);
            dialog.dismiss();
        }
    };

    @Override
    public void processAfterArchiveInboxMessage()
    {
        showToastMessage(R.string.message_archive_message_successfully);
        app.clearInboxNotification();
        finish();
    }

    private void initDialogQuickReply(Context context)
    {
        dlgReplyOption = new Dialog(context, R.style.dlg_quick_reply);
        dlgReplyOption.setContentView(R.layout.reply_option);
        dlgReplyOption.getWindow().setGravity(Gravity.BOTTOM);

        btReplyoption = (Button) dlgReplyOption.findViewById(R.id.reply_option);
        btReplyoption.setOnClickListener(this);

        btReplyAlloption = (Button) dlgReplyOption.findViewById(R.id.reply_all_option);
        btReplyAlloption.setOnClickListener(this);

        btForwardoption = (Button) dlgReplyOption.findViewById(R.id.forward_option);
        btForwardoption.setOnClickListener(this);

        btCanceloption = (Button) dlgReplyOption.findViewById(R.id.cancel_option);
        btCanceloption.setOnClickListener(this);
    }

    private void showDialogReplyOption()
    {
        handler.post(new Runnable() {

            @Override
            public void run()
            {
                dlgReplyOption.show();
            }
        });
    }

    private void hideDialogReplyOption()
    {
        dlgReplyOption.dismiss();
    }

    // private String getSendName(ArrayList<FriendInfo> data) {
    // String sendName = "";
    // if (data.size() == 1) {
    // sendName += data.get(0).getUserName();
    // } else if (data.size() > 1) {
    // int size = data.size() - 1;
    // for (int i = 0; i < size; i++) {
    // sendName += data.get(i).getUserName() + ";";
    // }
    // sendName += data.get(size).getUserName();
    // }
    //
    // return sendName;
    // }

    private String getSendName(ArrayList<HashMap<String, String>> data)
    {
        String sendName = "";
        if (data.size() == 1)
        {
            sendName += data.get(0).get("Username");
        }
        else if (data.size() > 1)
        {
            int size = data.size() - 1;
            for (int i = 0; i < size; i++)
            {
                sendName += data.get(i).get("Username") + ";";
            }
            sendName += data.get(size).get("Username");
        }
        return sendName;
    }

    private void getValueForSendMessage()
    {
        ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

        // from
        from = mainMessage.getMessageFromUserName();

        // to
        list = mainMessage.getMessageTos();
        sendToUserNames = getSendName(list);
        toUserNames = StringUtility.convertStringToXmppUsers(sendToUserNames);

        // cc
        list = mainMessage.getMessageBccs();
        sendCcUserNames = getSendName(list);
        ccUserNames = StringUtility.convertStringToXmppUsers(sendCcUserNames);

        // bcc
        list = mainMessage.getMessageCCs();
        sendBccUserNames = getSendName(list);
        bccUserNames = StringUtility.convertStringToXmppUsers(sendBccUserNames);

        // subject
        subject = ParserUtility.encodeStringValue(mainMessage.getMessageSubject());

        // content
        content = ParserUtility.encodeStringValue(mainMessage.getMessageContent());

        isDraft = mainMessage.getIsForward() == 1 ? true : false;
        isReply = mainMessage.getIsRepply() == 1 ? true : false;
        isForward = mainMessage.getIsForward() == 1 ? true : false;
        String tmp = mainMessage.getThreadId();

        threadId = tmp == null ? "" : tmp;

        messageIdBefore = mainMessage.getMessageId();
    }

    private static boolean isResend = false;
    private static boolean isResendFromDraft = false;
    private static String personalMessageID = "";

    /**
     * Send user message
     */
    private void sendMessage()
    {
        UserInfo userInfo = MedtalkSharedPreferences.getInstance(
            getApplicationContext()).getUserInfo();
        String token = userInfo.getAccessToken();

        getValueForSendMessage();
        isResend = true;
        isDraft = false;
        isReply = false;
        isForward = false;
        threadId = "";
        personalMessageID = "";
        isResendFromDraft = false;

        List<NameValuePair> parameters = ParameterFactory.createSendMessageParams(
            token, from, sendToUserNames, sendCcUserNames, sendBccUserNames,
            subject, content, isDraft, isReply, isForward, threadId,
            messageIdBefore, personalMessageID, isResendFromDraft, isResend);

        // Implement sign in post method
        AsyncHttpPost post = new AsyncHttpPost(self,
            new AsyncHttpResponseProcess(self) {

                @Override
                public void processIfResponseSuccess(String response)
                {
                    processSendMessageSuccess(response);
                }

            }, parameters);
        post.execute(WebServiceConfig.URL_SEND_COMPOSE_MESSAGE);
    }

    /**
     * Send new message notification
     * 
     * @param response
     */
    private void processSendMessageSuccess(String response)
    {
        // // Create new xmpp notification message
        // String content = XmppManager.createNewBodyData();

        // Create new xmpp notification message content
        ProfileInfo myProfile = MedtalkSharedPreferences.getInstance(
            getApplicationContext()).getProfileInfo();
        String fullName = (myProfile != null) ? myProfile.getFullNamePosition()
            : "";
        String subjectContent = (mainMessage != null && mainMessage.getMessageSubject() != null) ? mainMessage.getMessageSubject()
            : "";
        subjectContent = (subjectContent.length() > 30) ? subjectContent.substring(
            0, 29)
            + "..."
            : subjectContent;
        String content = XmppManager.createNewBodyData(fullName, subjectContent);

        // Send new message notification
        if (!app.sendXmppMessage(toUserNames, subjectContent, content)
            || !app.sendXmppMessage(ccUserNames, subjectContent, content)
            || !app.sendXmppMessage(bccUserNames, subjectContent, content))
        {
            showDialog(
                R.string.message_error_to_send_message_to_multiple_users,
                R.string.button_ok, null);
        }
        else
        {
            showToastMessage(getString(R.string.message_send_message_successfully));
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        webView.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);
        webView.restoreState(savedInstanceState);
    }

}